package com.ruoyi.staff.controller;

import java.io.IOException;
import java.util.List;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.domain.entity.SysProject;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.staff.domain.*;
import com.ruoyi.staff.service.IFamilyMemberService;
import com.ruoyi.staff.service.IStaffFileService;
import com.ruoyi.staff.service.IUploadFileService;
import com.ruoyi.system.service.ISysProjectService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.staff.service.IStaffBaseinfoService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 员工基础信息Controller
 * 
 * @author bzs
 * @date 2021-08-22
 */
@Controller
@RequestMapping("/staff/baseinfo")
public class StaffBaseinfoController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(StaffBaseinfoController.class);

    private String prefix = "staff/baseinfo";

    @Autowired
    private IStaffBaseinfoService staffBaseinfoService;

    @Autowired
    private IUploadFileService uploadFileService;

    @Autowired
    private IStaffFileService staffFileService;

    @Autowired
    private ISysProjectService sysProjectService;

    @Autowired
    private IFamilyMemberService familyMemberService;


    @RequiresPermissions("staff:baseinfo:view")
    @GetMapping()
    public String baseinfo(ModelMap mmap)
    {
        SysProject sysProject = new SysProject();
        List<SysProject> sysProjectList = sysProjectService.selectSysProjectList(sysProject);
        mmap.put("sysProjectList", sysProjectList);
        return prefix + "/baseinfo";
    }

    /**
     * 查询员工基础信息列表
     */
    @RequiresPermissions("staff:baseinfo:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(StaffBaseinfo staffBaseinfo)
    {
        startPage();
        //获取当前用户下所有项目id集合
//        List<String> projectIds = xxxxx(ShiroUtils.getUserId());
//        staffBaseinfo.setProjectIds(projectIds);
        List<StaffBaseinfo> list = staffBaseinfoService.selectStaffBaseinfoList(staffBaseinfo);
        return getDataTable(list);
    }

    /**
     * 保存家庭成员信息
     */
    @PostMapping("/saveFamilyMember")
    @ResponseBody
    public AjaxResult saveFamilyMember(FamilyMember familyMember)
    {
        return toAjax(familyMemberService.insertFamilyMember(familyMember));
    }

    /**
     * 上传证书附件（证书附件不同于合同附件，证书可能有多种，所以这里用map来放）
     */
    @PostMapping("/importCertificate")
    @ResponseBody
    public AjaxResult importCertificate(MultipartFile file, String stfIds){
        //baseinfo要了有什么用
        StaffBaseinfo baseinfo = staffBaseinfoService.selectStaffBaseinfoById(Long.valueOf(stfIds));
        if(!file.isEmpty()){
            try {
                //取得证书地址
                String certificate = FileUploadUtils.upload(Global.getCertificatePath(),file);
                //将证书附件地址放到证书的地址属性中
                UploadFile uploadFile = new UploadFile();
                uploadFile.setStfId(baseinfo.getStfId());
                uploadFile.setFileId(UUID.randomUUID().toString());
                uploadFile.setFileName(file.getOriginalFilename());
                uploadFile.setFilePath(certificate);
                //？？目前文件可以上传，但是关于文件的一些信息不能存到数据库中
              int a = uploadFileService.insertUploadFile(uploadFile);
              logger.info("存入"+a+"组数据");
            } catch (IOException e) {
                e.printStackTrace();
                return AjaxResult.error("上传失败，请查看后台日志");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 下载证书附件
     */
    @PostMapping("/exportCertificate")
    @ResponseBody
    public AjaxResult exportCertificate(String stfId, HttpServletRequest request, HttpServletResponse response){
        //1，根据工号去upload_file库里查询文件地址
        UploadFile uploadFile = new UploadFile();
        uploadFile.setStfId(Long.valueOf(stfId));
        List<UploadFile> listFile = uploadFileService.selectUploadFileList(uploadFile);
        uploadFile = listFile.get(0);
        String filePath = uploadFile.getFilePath();
        filePath = filePath.replaceAll("/profile", Global.getProfile());
        return AjaxResult.success("success",filePath);
    }

    //接上面


    /**
     * 导入员工合同列表
     * */
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("staff:baseinfo:import")
    @PostMapping("/importExcel")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<StaffBaseinfo> util = new ExcelUtil<>(StaffBaseinfo.class);
        List<StaffBaseinfo> lists = util.importExcel(file.getInputStream());
        SysUser sysUser = ShiroUtils.getSysUser();
        //校验数据
        String res = staffBaseinfoService.validateDatas(lists);
        if (StringUtils.isNotBlank(res)){
            return AjaxResult.error(res);
        }
        String message =staffBaseinfoService.importcontractRelations(lists,updateSupport,sysUser);
        return AjaxResult.success(message);
    }


    /**
     * 导入中的下载模板
     * */
    @RequiresPermissions("staff:baseinfo:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<StaffBaseinfo> util = new ExcelUtil<StaffBaseinfo>(StaffBaseinfo.class);
        return util.importTemplateExcel("员工基础信息");
    }


    /**
     * 导出员工基础信息列表
     */
    @RequiresPermissions("staff:baseinfo:export")
    @Log(title = "员工基础信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(String ids)
    {
        String[] stfIds = Convert.toStrArray(ids);
        List<StaffBaseinfo> list = staffBaseinfoService.selectStaffBaseinfoListByIds(stfIds);
        ExcelUtil<StaffBaseinfo> util = new ExcelUtil<StaffBaseinfo>(StaffBaseinfo.class);
        return util.exportExcel(list, "baseinfo");
    }

    /**
     * 新增员工基础信息
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        SysProject sysProject = new SysProject();
        List<SysProject> sysProjectList = sysProjectService.selectSysProjectList(sysProject);
        mmap.put("sysProjectList", sysProjectList);
        return prefix + "/add";
    }

    /**
     * 新增保存员工基础信息
     */
    @RequiresPermissions("staff:baseinfo:add")
    @Log(title = "员工基础信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(StaffBaseinfo staffBaseinfo)
    {
        if(staffBaseinfoService.checkStaffExist(staffBaseinfo.getIdCard())){
            return AjaxResult.error("身份证号已经存在，请勿重复添加!");
        }else {
            return toAjax(staffBaseinfoService.insertStaffBaseinfo(staffBaseinfo));
        }
    }

    /**
     * 修改员工基础信息
     */
    @GetMapping("/edit/{stfId}")
    public String edit(@PathVariable("stfId") String stfId, ModelMap mmap)
    {
        StaffBaseinfo staffBaseinfo = staffBaseinfoService.selectStaffBaseinfoById(Long.valueOf(stfId));
        mmap.put("staffBaseinfo", staffBaseinfo);
        SysProject sysProject = new SysProject();
        List<SysProject> sysProjectList = sysProjectService.selectSysProjectList(sysProject);
        mmap.put("sysProjectList", sysProjectList);
        return prefix + "/edit";
    }

    /**
     * 修改保存员工基础信息
     */
    @RequiresPermissions("staff:baseinfo:edit")
    @Log(title = "员工基础信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(StaffBaseinfo staffBaseinfo)
    {
        return toAjax(staffBaseinfoService.updateStaffBaseinfo(staffBaseinfo));
    }

    /**
     * 删除员工基础信息
     */
    @RequiresPermissions("staff:baseinfo:remove")
    @Log(title = "员工基础信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String[] ids)
    {
        return toAjax(staffBaseinfoService.deleteStaffBaseinfoByIds(ids));
    }

    @GetMapping("/import/{stfId}")
    public String toImport(@PathVariable Long stfId,ModelMap modelMap){
        List<StaffFile> staffFiles = staffFileService.selectStaffFilesById(stfId);
        modelMap.put("staffFiles",staffFiles);
        modelMap.put("stfId",stfId);
        return prefix + "/import";
    }
}
